package com.keya.dicomtask;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.keya.base.WorkSpace;
import com.keya.base.output.ResultData;
import com.keya.device.GatewayProperties;
import com.keya.features.dicom.DicomFileUtils;
import com.keya.mapper.DicomTaskMapper;
import com.keya.utils.ArchiveUtils;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.*;

@Service
@Slf4j
public class DicomTaskService extends ServiceImpl<DicomTaskMapper, DicomTask> {

    @Resource
    GatewayProperties gateWayProperties;
    @Resource
    DicomUploadProperties dicomUploadProperties;
    @Resource
    VersionGenerator versionGenerator;
    @Resource
    DicomTaskMapper dicomTaskMapper;
    public static final String FILE_SPLIT = "/";

    @Transactional(rollbackFor = RuntimeException.class)
    public ResultData upload(String aetitle, MultipartFile[] files) {
        WorkSpace workSpace = new WorkSpace(dicomUploadProperties.getPath());
        try {
            if (files.length == 0) {
                return ResultData.fail("数据为空。");
            }
            workSpace.prepare();
            for (MultipartFile multipartFile : files) {
                File file = com.keya.utils.FileUtil.asFile(multipartFile.getInputStream(), Paths.get(workSpace.getPath(), multipartFile.getOriginalFilename()).toString());
                if (ArchiveUtils.isArchive(file)) {
                    ArchiveUtils.unarchive(file, workSpace.getPath());
                    FileUtils.forceDelete(file);
                }
            }
            if (StringUtils.isEmpty(aetitle)) {
                aetitle = dicomUploadProperties.getAetitle();
            }
            List<DcmInfoBO> dcmInfoBOS = storeDcm(workSpace.getPath(), aetitle);
            Map<String, DcmInfoBO> studyMap = new HashMap<>();
            for (DcmInfoBO dcmInfoBO : dcmInfoBOS) {
                if (studyMap.get(dcmInfoBO.getStudyInstanceUID()) != null) {
                    continue;
                }
                studyMap.put(dcmInfoBO.getStudyInstanceUID(), dcmInfoBO);
            }
            for (String key : studyMap.keySet()) {
                save(studyMap.get(key));
            }
            return ResultData.success(studyMap.keySet());
        } catch (Exception e) {
            e.printStackTrace();
            return ResultData.fail(e.getMessage());
        }
    }

    public void save(DcmInfoBO dcmInfoBO){
        Integer version = versionGenerator.getVersion();
        String aeTitle = dcmInfoBO.getAetitle();
        String AccessionNumber = dcmInfoBO.getAccessionNumber();
        String StudyInstanceUID = dcmInfoBO.getStudyInstanceUID();
        String path = gateWayProperties.getStorage()
                + File.separator + aeTitle
                + File.separator + AccessionNumber
                + File.separator + StudyInstanceUID;
        LambdaQueryWrapper<DicomTask> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(DicomTask::getAeTitle, aeTitle)
                .eq(DicomTask::getAccessionNumber, AccessionNumber)
                .eq(DicomTask::getStudyInstanceUID, StudyInstanceUID);
        DicomTask d = dicomTaskMapper.selectOne(wrapper);
        if (ObjectUtil.isNotEmpty(d)) {
            d.setVersion(version)
                    .setMark(0)
                    .setPath(path)
                    .setTransmissionAt(new Date())
                    .setUpdatedAt(new Date());
            dicomTaskMapper.updateById(d);
            log.info(String.format("dicomTask进行更新：%s", StudyInstanceUID));
        } else {
            DicomTask dicomTask = new DicomTask()
                    .setAeTitle(aeTitle)
                    .setAccessionNumber(AccessionNumber)
                    .setStudyInstanceUID(StudyInstanceUID)
                    .setPath(path)
                    .setVersion(version)
                    .setMark(0)
                    .setCreatedAt(new Date()).setTransmissionAt(new Date()).setUpdatedAt(new Date());
            dicomTaskMapper.insert(dicomTask);
            log.info(String.format("dicomTask进行新增：%s", StudyInstanceUID));
        }
    }


    private List<DcmInfoBO> storeDcm(String sourcePath, String aeTitle) {
        File file = new File(sourcePath);
        List<DcmInfoBO> result = new ArrayList<>();
        if (!file.exists()) {
            return result;
        }
        if (file.isDirectory()) {
            File[] files = file.listFiles();
            if (files != null) {
                for (File son : files) {
                    result.addAll(storeDcm(son.getPath(), aeTitle));
                }
            }
        } else {
            DcmInfoBO dcmInfoBO = DicomFileUtils.getDcmInfoBO(file);
            if (dcmInfoBO != null) {
                result.add(dcmInfoBO);
                dcmInfoBO.setAetitle(aeTitle);
                Path path = Paths.get(gateWayProperties.getStorage(),
                        aeTitle, dcmInfoBO.getAccessionNumber(), dcmInfoBO.getStudyInstanceUID(),
                        dcmInfoBO.getSeriesInstanceUID());
                File dcmFile = new File(path + FILE_SPLIT + dcmInfoBO.getSOPInstanceUID() + ".dcm");
                FileUtil.move(file, dcmFile, true);
            }
        }
        return result;
    }
}
